//外部集
const fs = require("fs")
const program = require("commander")
const { promisify } = require("util")
const download = promisify(require("download-git-repo"))

//内部集
const { VUE_REPO } = require("../config/repo")
const start = require("../utils/start")
const { log } = require("console")
const compileEjs = require("../utils/compile")

//方法集
//方法: 1.创建项目 -->  gcli create [project]
async function createProjectAction(project) {
  try {
    //1.下载模板
    await download(VUE_REPO, project, { clone: true })
    //2.提示创建成功
    console.log(`创建项目 ${project} 成功！`)
    //解决windows系统下npm install报错问题
    //console.log(process.platform)
    const commandName = process.platform === "win32" ? "npm.cmd" : "npm"
    //3.帮助执行npm install
    await start(commandName, ["install"], {
      cwd: `./${project}`,
      stdio: "inherit",
    })

  
    //4.提示执行npm run dev
    await start(commandName, ["run", "dev"], {
      cwd: `./${project}`,
      stdio: "inherit",
    })
  } catch (error) {
    console.log("创建项目失败,请重新尝试一下~")
  }
}

//方法: 2.添加组件 --> gcli add [cpnname]
async function addComponentAction(cpnname) {
  //console.log(cpnname) //获取add后面的参数->cpnname
  //console.log(program.opts().dest);  //获取额外的参数->dest路径
  //1. 根据模版内容给组件填充数据
  const result = await compileEjs('vuecmp.ejs', {
    name: cpnname ,
    lowerName:cpnname.toLowerCase()
  })
  //2. 写入文件 
  const dest = program.opts().dest || "src/components"
  await fs.promises.writeFile(`${dest}/${cpnname}.vue`, result)
  console.log("创建组件成功:", cpnname + ".vue")
}

//导出
module.exports = {
  createProjectAction,
  addComponentAction,
}
